package com.adouteam.simple.wechat.tool;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;

public class Encrypt{
    private static final Encrypt ME = new Encrypt();

    public static String encryptMD5(String originStr){
        return ME.encrypt(originStr, "MD5");
    }

    /**
     * SHA-1加密
     * 
     * @param originStr 原始内容
     * @return 加密后内容
     */
    public static String encryptSHA1(String originStr){
        return ME.encrypt(originStr, "SHA-1");
    }

    /**
     * SHA-256加密
     *
     * @param originStr 原始内容
     * @return 加密后内容
     */
    public static String encryptSHA256(String originStr){
        return ME.encrypt(originStr, "SHA-256");
    }

    private String encrypt(String originStr, String algorithm){
        if(StringUtils.isBlank(originStr)){
            return "";
        }
        String resultStr = "";
        if(StringUtils.isBlank(algorithm)){
            algorithm = "MD5";
        }
        try{
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] originByte = originStr.getBytes(Charset.defaultCharset());
            md.update(originByte);
            resultStr = String.valueOf(Hex.encodeHex(md.digest()));
        }catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return resultStr;
    }
}
